'use strict';
const fs = require('fs');
const path = require('path');
let config = require('./config.json')
const PngCompressor = require('./pngCompressor')
const project_path = Editor.Project.path;
const config_file = 'png_compressor_config.json';
const config_path = path.join(project_path, config_file)

let cfg = null
// console.log = Editor.log
// console.warn = Editor.warn
// console.error = Editor.error

function onBeforeBuildFinish(options, callback) {
  // Editor.log("onBeforeBuildFinish", options)
  let dest = options.dest;
  dest = dest.replace(/\\\\/, '\/')
  dest = dest.replace(/\\/, '\/')
  // Editor.log('dest', dest)
  if (config.isBuildFinshCompress) {
    const pngCompressor_inst = new PngCompressor(cfg);
    pngCompressor_inst.buildCompress(dest + '/res/', function () {
      callback();
    })
  } else {
    callback();
  }

}

function init_config() {
  Editor.log('project_path', project_path)
  Editor.log('config_path', config_path)
  if (!fs.existsSync(config_path)) {
    fs.copyFileSync(path.join(__dirname, 'config.json'), config_path);
  }
  cfg = require(config_path)
}

function init() {
  init_config()
}
let cur_compresor = null;
module.exports = {
  load() {
    init();
    Editor.Builder.on('before-change-files', onBeforeBuildFinish);
  },

  unload() {
    Editor.Builder.removeListener('before-change-files', onBeforeBuildFinish);
    Editor.Panel.close('png_compressor');
  },

  // register your ipc messages here
  messages: {
    'setting'() {
      Editor.Panel.open('png_compressor');
    },
    'readConfig'(event) {
      Editor.log('readConfig................', event.reply);
      let data_str = fs.readFileSync(config_path);
      if (data_str) {
        try {
          cfg = JSON.parse(data_str)
        } catch (e) {

        }
      }
      if (event.reply && data_str) {
        event.reply(null, data_str);
      } else {
        event.reply('没配置文件');
      }
    },
    'writeConfig'(event, data_str) {
      Editor.log('writeConfig................', event.reply);
      fs.writeFileSync(config_path, data_str);
      // Editor.assetdb.refresh("db://assets/../" + config_file);
      if (event.reply) {
        event.reply(null, data_str);
      } else {
        event.reply('没配置文件');
      }
    },
    'startCompress'() {
      Editor.log('startCompress');
      const pngCompressor_inst = new PngCompressor(cfg);
      pngCompressor_inst.getConfigUncompressedImgPathList(config.compressPathList, (list) => {
        Editor.log('startCompress list', list.length, list)
        pngCompressor_inst.compressAll(list, false);
      });
    },
    'startCompressForce'() {
      Editor.log('startCompressForce');
      const pngCompressor_inst = new PngCompressor(cfg);
      pngCompressor_inst.getConfigAllImgPathList(config.compressPathList, (list) => {
        Editor.log('startCompressForce', list.length, list)
        pngCompressor_inst.compressAll(list, false);
      });
    },
    'compressWithConfig'(event, cfg, progress_cb) {
      const pngCompressor_inst = new PngCompressor(cfg);
      function get_list(callback) {
        if (cfg.ignore_compressed_png) {
          pngCompressor_inst.getConfigUncompressedImgPathList(config.compressPathList, (list) => {
            if (callback) callback(list)
          });
        } else {
          pngCompressor_inst.getConfigAllImgPathList(config.compressPathList, (list) => {
            if (callback) callback(list)
          });
        }
      }
      let reply = event.reply;
      get_list((list) => {
        Editor.log('compresser 开始压缩', event, cfg)
        if (list.length == 0) {
          reply(null, 100);
        }
        pngCompressor_inst.compressAll(list, false, (idx, max, img, beforeSize, nowSize) => {
          let percent = idx / max * 100;
          // Editor.log('progress_cb', percent);
          // Editor.Ipc.sendToPanel('png_compressor', 'hello', 'you got me' + percent, function (e, cb) {
          // }, -1)
          Editor.log('set_compress_progress', idx)
          Editor.Ipc.sendToPanel('png_compressor', 'set_compress_progress', percent, img, beforeSize, nowSize, function (e, cb) {

          }, -1)
        }, (rate) => {
          Editor.Ipc.sendToPanel('png_compressor', 'set_compress_progress', 100, function (e, cb) { }, -1)
          reply(null, 100, rate);
        });
      });
    },
    'send_hello'() {
      Editor.Ipc.sendToPanel('png_compressor', 'hello', 'you got me', function (e, cb) {

      }, -1)
    }
  },
};
// {"compressPathList":["assets/"],"compressType":0,"tinify_key":"41qYRVZY3Zd0Cfm1P22zYw2bDMdJvPXb"}